//
//  UIApplication_Ex.swift
//  DawnFoundation
//
//  Created by 崔成成 on 2021/8/15.
//

import UIKit

extension UIApplication {
    
    var _keyWindow: UIWindow? {
        if #available(iOS 13.0, *) {
            if let kw = UIApplication.shared.windows.filter({ $0.isKeyWindow }).last {
                return kw
            }
            return UIApplication.shared.connectedScenes
                .filter({ $0.activationState == .foregroundActive })
                .map({ $0 as? UIWindowScene })
                .compactMap({ $0 })
                .last?.windows
                .filter({ $0.isKeyWindow })
                .last
        }
        return UIApplication.shared.keyWindow
    }
    
    var currentVC: UIViewController? {
        guard let rootVC = _keyWindow?.rootViewController else { return nil }
        if let tbc = rootVC as? UITabBarController {
            if let nc = rootVC as? UINavigationController {
                return nc.viewControllers.last
            }
            return tbc
        }else if let nc = rootVC as? UINavigationController {
            return nc.viewControllers.last
        }
        return rootVC
    }
}
